package at.fhv.androideightpuzzle.network;

import java.io.IOException;
import java.util.Observable;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import at.fhv.androideightpuzzle.network.message.IMessage;
import at.fhv.androideightpuzzle.network.messageparsers.GameResultMessageParser;
import at.fhv.androideightpuzzle.network.messageparsers.IMessageParser;
import at.fhv.androideightpuzzle.network.messageparsers.JoinGameMessageParser;
import at.fhv.androideightpuzzle.network.messageparsers.PuzzleSolvedMessageParser;
import at.fhv.androideightpuzzle.network.messageparsers.StartPuzzleMessageParser;

public abstract class NetworkSocket extends Observable{
	
	protected ConnectionType m_connType;
	
	protected IMessageParser[] m_messageParsers;
	
	public NetworkSocket(ConnectionType type){
		m_connType=type;
		
		m_messageParsers=new IMessageParser[]{
				new GameResultMessageParser(),
				new JoinGameMessageParser(),
				null,
				new PuzzleSolvedMessageParser(),
				new StartPuzzleMessageParser()};
	}
	
	public abstract void connect(String host) throws IOException;
	
	public abstract void sendMessage(IMessage message) throws IOException;
	
	public abstract void close() throws IOException;
	
	public abstract boolean isAlive();
	
	protected void parseMessage(String msgString){
		android.util.Log.d("NetworkSocket", "parse message");
		try{
			JSONParser parser=new JSONParser();
			JSONObject jsonObj=(JSONObject)parser.parse(msgString);
			
			int type=((Number)jsonObj.get("type")).intValue();
			
			IMessage message=m_messageParsers[type].parseMessage(jsonObj);
			
			setChanged();
			notifyObservers(message);
		}catch(ParseException exc){
			android.util.Log.e("NetworkSocket",exc.getMessage(),exc);
		}
	}
	
	public ConnectionType getConnectionType(){
		return m_connType;
	}
}
